package com.javasm.sale.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.commons.entity.CrmProperties;
import com.javasm.commons.enums.E;
import com.javasm.commons.exceptions.MvcException;
import com.javasm.commons.util.Constants;
import com.javasm.commons.util.DocxUtil;
import com.javasm.sale.CommodityOrder;
import com.javasm.sale.Delivery;
import com.javasm.sale.GoodsDelivery;
import com.javasm.sale.Order;
import com.javasm.sale.dao.DeliveryDao;
import com.javasm.sale.service.CommodityDeliveryService;
import com.javasm.sale.service.DeliveryService;
import com.javasm.sale.service.OrderService;
import com.javasm.sys.CurrentLogin;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeliveryServiceImpl extends ServiceImpl<DeliveryDao, Delivery> implements DeliveryService {
    @Resource
    private CommodityDeliveryService commodityDeliveryService;
    @Resource
    private OrderService orderService;

    @Override
    public Delivery getDeliveryAndGoodsList(String id) {
        Delivery d = getById(id);
        Order order = orderService.getById(d.getOrderId());
        List<GoodsDelivery> l = commodityDeliveryService.listGoods(d.getDeliveryId());
        d.setOrder(order);
        d.setGoodsDeliveryList(l);
        return d;
    }

    @Override
    public List<Delivery> listDeliveryAndOrder(Delivery obj) {

        return this.baseMapper.listDeliveryAndOrder(obj);
    }

    //启用事务
    @Transactional
    @Override
    public byte[] addAndCreateDeliveryWord(Order order) throws IOException {
        if(!order.getStatus().equals(Constants.PAID)) new MvcException(E.NO_ORDER_STATUS);

        //1.添加出库表 根据订单的id
        Delivery delivery = new Delivery();
        delivery.setOrderId(order.getOrderId());
        delivery.setCreateId(CurrentLogin.getLoginUser().getUserId()+"");
        baseMapper.insert(delivery);

        //3.把订单表状态改为待出库
        UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
        orderUpdateWrapper.set("status", Constants.WAIT_DELIVERY);
        orderUpdateWrapper.eq("order_id",order.getOrderId());
        orderService.update(orderUpdateWrapper);

        //接着就要返回word了
        return createDeliveryDocx(order,delivery);
    }

    private byte[] createDeliveryDocx(Order order,Delivery delivery) throws IOException {
        String path = CrmProperties.getRoot()+ "/出库单"+System.currentTimeMillis()+"_"+ CurrentLogin.getLoginUserName()+".docx";
        Map<String, Object> map = new HashMap<>();
        map.put("deliveryId",delivery.getDeliveryId());
        map.put("createName" , CurrentLogin.getLoginUserName());
        map.put("nowTime" , DateUtil.now());
        map.put("commodityList",order.getCommodityList());
        DocxUtil.createDocx(map,"出库表.xml",new FileOutputStream(path));
        FileInputStream fileInputStream = new FileInputStream(path);
        byte[] bytes = IoUtil.readBytes(fileInputStream);
//        new File(path).delete();
        return bytes;
    }

    @Transactional
    @Override
    public void deliveryFinish(Order order){
        String orderId = order.getOrderId();

        //1.本不用查询 是在出库记录表中提交的
        QueryWrapper<Delivery> qw = new QueryWrapper<>();
        qw.select("delivery_id").eq("order_id",orderId);
        Delivery delivery  = this.getOne(qw);

        //2.给出库单添加物流单号 把物流单号添加到该出库表中
        delivery.setTrackingNumber(IdUtil.objectId());
        boolean b = updateById(delivery);

        //3.添加中间表 sale_commodity_delivery 的数据 根据 order内的商品id 和数量
        //mybatis plus 会把主键再set会实体中 我们直接获取就好
        // 并且给每个商品添加商品串号 以供查询
        List<GoodsDelivery> commodityDeliveries = new ArrayList<>();
        String deliveryId = delivery.getDeliveryId();
        for (CommodityOrder commodity : order.getCommodityList()) {
            for (int i = 0; i < commodity.getNum(); i++) {
                GoodsDelivery cd = new GoodsDelivery();
                cd.setOneMoney(commodity.getOneMoney());
                cd.setGcode(commodity.getGcode());
                cd.setDeliveryId(deliveryId);
                cd.setImea(IdUtil.objectId());
                commodityDeliveries.add(cd);
            }
        }
        commodityDeliveryService.saveBatch(commodityDeliveries);

        //4.修改订单表的状态
        UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
        orderUpdateWrapper.set("status", Constants.DELIVERY_ING);
        orderUpdateWrapper.eq("order_id",orderId);
        orderService.update(orderUpdateWrapper);
    }




}

